﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Xml;

namespace BasicHttpSohu
{
    public class ApiService
    {
        /// <summary>
        /// 删除一条私信
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="id"></param>
        /// <param name="type"></param>
        public static void DeleteMessage(string name, string pwd, string id, string type)
        {
            string url = string.Format("http://api.t.sohu.com/direct_messages/destroy/{0}.xml?type={1}", id, type);
            WebRequest request = WebRequest.Create(url);
            request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(name + ":" + pwd));
            request.Method = "DELETE";
            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    string xml = sr.ReadToEnd();
                }
            }
        }
        /// <summary>
        /// 发送私信
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="target_id"></param>
        /// <param name="text"></param>
        public static void New(string name, string pwd, string target_id, string text)
        {
            string url = "http://api.t.sohu.com/direct_messages/new.xml";
            string postData = string.Format("user={0}&text={1}", target_id, HttpUtility.UrlEncode(text));
            string xml = HttpPost(name, pwd, url, postData);
            if (xml.Contains("<error>"))
                throw new Exception("传递纸条错误！");
        }
        /// <summary>
        /// 查看我发出的私信列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static List<DirectMessage> Sent(string name, string pwd)
        {
            string url = "http://api.t.sohu.com/direct_messages/sent.xml?page=1&count=30";
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取发件箱列表失败");
            List<DirectMessage> lst = GetDirectMessage(xml);
            return lst;
        }
        /// <summary>
        /// 查看我收到的私信列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static List<DirectMessage> Recipient(string name, string pwd)
        {
            string url = "http://api.t.sohu.com/direct_messages.xml?page=1&count=30";
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取收件箱列表失败");
            List<DirectMessage> lst = GetDirectMessage(xml);
            return lst;
        }
        /// <summary>
        /// 获取私信列表
        /// </summary>
        /// <param name="xml"></param>
        private static List<DirectMessage> GetDirectMessage(string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList list = doc.SelectNodes("/direct-messages/direct_message");
            List<DirectMessage> lst = new List<DirectMessage>();
            foreach (XmlNode node in list)
            {
                DirectMessage dm = new DirectMessage();
                dm.id = node.SelectSingleNode("id").InnerText;
                dm.sender_id = node.SelectSingleNode("sender_id").InnerText;
                dm.text = node.SelectSingleNode("text").InnerText.Replace("&lt;a target='_blank' href='http://t.itc.cn/GGhY'&gt;帮助&lt;/a&gt;", "帮助");
                dm.recipient_id = node.SelectSingleNode("recipient_id").InnerText;
                string createDt = node.SelectSingleNode("created_at").InnerText;
                if (!string.IsNullOrEmpty(createDt))
                {
                    string[] sdtArr = createDt.Split(' ');
                    string newDt = string.Format("{0}, {1} {2} {3} {4}", sdtArr[0], sdtArr[2], sdtArr[1], sdtArr[5], sdtArr[3]);
                    dm.created_at = DateTime.Parse(newDt);
                }
                dm.sender_screen_name = node.SelectSingleNode("sender_screen_name").InnerText;
                dm.recipient_screen_name = node.SelectSingleNode("recipient_screen_name").InnerText;
                lst.Add(dm);
            }
            return lst;
        }
        /// <summary>
        /// 关注目标用户
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="target_id"></param>
        public static void Create(string name, string pwd, string target_id)
        {
            string url = string.Format("http://api.t.sohu.com/friendship/create/{0}.xml", target_id);
            string xml = HttpPost(name, pwd, url, "");
            if (xml.Contains("<error>"))
                throw new Exception("获取关注情况失败！");
        }

        /// <summary>
        /// 取消对目标用户的关注
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="target_id"></param>
        public static void Destory(string name, string pwd, string target_id)
        {
            string url = string.Format("http://api.t.sohu.com/friendships/destroy/{0}.xml", target_id);
            string xml = HttpPost(name, pwd, url, "");
            if (xml.Contains("<error>"))
                throw new Exception("取消关注失败！");
        }
        /// <summary>
        /// 查看用户a是否关注用户b
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="user_a">我的ID</param>
        /// <param name="user_b"></param>
        /// <returns></returns>
        public static bool Friendship(string name, string pwd, string user_a, string user_b)
        {
            string url = string.Format("http://api.t.sohu.com/friendship/exists.xml?user_a={0}&user_b={1}", user_a, user_b);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取关注情况失败！");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNode node = doc.SelectSingleNode("/friends");
            if (node != null)
                return bool.Parse(doc.SelectSingleNode("/friends").InnerText);
            else
                return false;
        }
        /// <summary>
        /// 获取粉丝列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static List<User> Followers(string name, string pwd)
        {
            string url = "http://api.t.sohu.com/statuses/followers.xml?page=1&count=20";
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取粉丝列表失败！");
            List<User> lstUser = new List<User>();
            lstUser.AddRange(GetUser(xml));
            if (lstUser.Count < 20)
                return lstUser;
            url = "http://api.t.sohu.com/statuses/followers.xml?page=2&count=20";
            xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取粉丝列表失败！");
            lstUser.AddRange(GetUser(xml));
            return lstUser;
        }
        /// <summary>
        /// 获取好友列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static List<User> Friends(string name, string pwd)
        {
            string url = "http://api.t.sohu.com/statuses/friends.xml?page={0}&count=20";
            List<User> lstUser = new List<User>();
            for (int i = 1; lstUser.Count % 20 == 0; i++)
            {
                string xml = HttpGet(name, pwd, string.Format(url, i));
                if (xml.Contains("<error>"))
                    throw new Exception("获取关注列表失败！");
                lstUser.AddRange(GetUser(xml));
            }
            return lstUser;
        }
        /// <summary>
        /// 得到用户信息
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private static List<User> GetUser(string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList list = doc.SelectNodes("/users/user");
            List<User> lstUser = new List<User>();
            foreach (XmlNode node in list)
            {
                User user = new User();
                user.id = node.SelectSingleNode("id").InnerText;
                user.screen_name = node.SelectSingleNode("screen_name").InnerText;
                user.name = node.SelectSingleNode("name").InnerText;
                user.location = node.SelectSingleNode("location").InnerText;
                user.description = node.SelectSingleNode("description").InnerText;
                user.url = node.SelectSingleNode("url").InnerText;
                user.profile_image_url = node.SelectSingleNode("profile_image_url").InnerText;
                user._protected = bool.Parse(node.SelectSingleNode("protected").InnerText);
                user.followers_count = node.SelectSingleNode("followers_count").InnerText;
                user.friends_count = node.SelectSingleNode("friends_count").InnerText;
                user.favourites_count = node.SelectSingleNode("favourites_count").InnerText;
                user.statuses_count = node.SelectSingleNode("statuses_count").InnerText;
                user.following = bool.Parse(node.SelectSingleNode("following").InnerText);
                user.verified = bool.Parse(node.SelectSingleNode("verified").InnerText);
                user.contributors_enabled = bool.Parse(node.SelectSingleNode("contributors_enabled").InnerText);
                lstUser.Add(user);
            }
            return lstUser;
        }
        /// <summary>
        /// 删除一条微博
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="status_id"></param>
        public static void Delete(string name, string pwd, string status_id)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/destroy/{0}.xml", status_id);
            WebRequest request = WebRequest.Create(url);
            request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(name + ":" + pwd));
            request.Method = "DELETE";
            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    string xml = sr.ReadToEnd();
                    if (xml.Contains("<error>"))
                        throw new Exception("删除微博失败！");
                }
            }
        }
        /// <summary>
        /// 发布图片微博
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="status"></param>
        /// <param name="file">图片文件，转化成字节数组</param>
        /// <returns></returns>
        public static string UploadImg(string name, string pwd, string status, byte[] file)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            //req
            WebRequest req = System.Net.WebRequest.Create(@"http://api.t.sohu.com/statuses/upload.xml");
            req.Method = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            req.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(name + ":" + pwd));

            //head参数
            StringBuilder sb = new StringBuilder();
            sb.Append("--" + boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"status\"");
            sb.Append("\r\n\r\n");
            sb.Append(HttpUtility.UrlEncode(status));
            sb.Append("\r\n");

            sb.Append("--" + boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"pic\"; filename=\"wiki.jpg\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: image/pjpeg");
            sb.Append("\r\n\r\n");

            string head = sb.ToString();
            byte[] form_data = Encoding.UTF8.GetBytes(head);
            byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            //post总长度
            long length = form_data.Length + file.Length + foot_data.Length;
            req.ContentLength = length;

            using (Stream requestStream = req.GetRequestStream())
            {
                //头
                requestStream.Write(form_data, 0, form_data.Length);
                //内容
                requestStream.Write(file, 0, file.Length);
                //尾
                requestStream.Write(foot_data, 0, foot_data.Length);
            }

            using (WebResponse pos = req.GetResponse())
            {
                using (StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8))
                {
                    string xml = sr.ReadToEnd().Trim();
                    if (xml.Contains("<error>"))
                        throw new Exception("发布图片微博失败！");
                    return xml;
                }
            }
        }
        /// <summary>
        /// 得到一条微博的评论和转发数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="status_id"></param>
        /// <returns></returns>
        public static Count Counts(string name, string pwd, string status_id)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/counts/{0}.xml", status_id);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取评论和转发数失败！");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            Count count = new Count();
            count.comments_count = doc.SelectSingleNode("/count/comments_count").InnerText;
            count.transmit_count = doc.SelectSingleNode("/count/transmit_count").InnerText;
            return count;
        }
        /// <summary>
        /// 显示一条微博
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="status_id"></param>
        /// <returns></returns>
        public static Status Show(string name, string pwd, string status_id)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/show/{0}.xml", status_id);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("显示微博失败！");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNode node = doc.SelectSingleNode("/status");
            Status status = new Status();
            string createDt = node.SelectSingleNode("created_at").InnerText;
            if (!string.IsNullOrEmpty(createDt))
            {
                string[] sdtArr = createDt.Split(' ');
                string newDt = string.Format("{0}, {1} {2} {3} {4}", sdtArr[0], sdtArr[2], sdtArr[1], sdtArr[5], sdtArr[3]);
                status.created_at = DateTime.Parse(newDt);
            }
            status.id = node.SelectSingleNode("id").InnerText;
            status.text = node.SelectSingleNode("text").InnerText;
            status.source = node.SelectSingleNode("source").InnerText;
            status.favorited = node.SelectSingleNode("favorited").InnerText;
            status.truncated = bool.Parse(node.SelectSingleNode("truncated").InnerText);
            status.in_reply_to_status_id = node.SelectSingleNode("in_reply_to_status_id").InnerText;
            status.in_reply_to_user_id = node.SelectSingleNode("in_reply_to_user_id").InnerText;
            status.in_reply_to_screen_name = node.SelectSingleNode("in_reply_to_screen_name").InnerText;
            status.in_reply_to_status_text = node.SelectSingleNode("in_reply_to_status_text").InnerText;
            status.small_pic = node.SelectSingleNode("small_pic").InnerText;
            status.middle_pic = node.SelectSingleNode("middle_pic").InnerText;
            status.original_pic = node.SelectSingleNode("original_pic").InnerText;
            User user = new User();
            user.id = node.SelectSingleNode("user/id").InnerText;
            user.screen_name = node.SelectSingleNode("user/screen_name").InnerText;
            user.name = node.SelectSingleNode("user/name").InnerText;
            user.location = node.SelectSingleNode("user/location").InnerText;
            user.description = node.SelectSingleNode("user/description").InnerText;
            user.url = node.SelectSingleNode("user/url").InnerText;
            user.profile_image_url = node.SelectSingleNode("user/profile_image_url").InnerText;
            user._protected = bool.Parse(node.SelectSingleNode("user/protected").InnerText);
            user.followers_count = node.SelectSingleNode("user/followers_count").InnerText;
            user.friends_count = node.SelectSingleNode("user/friends_count").InnerText;
            user.favourites_count = node.SelectSingleNode("user/favourites_count").InnerText;
            user.statuses_count = node.SelectSingleNode("user/statuses_count").InnerText;
            user.following = bool.Parse(node.SelectSingleNode("user/following").InnerText);
            user.verified = bool.Parse(node.SelectSingleNode("user/verified").InnerText);
            user.contributors_enabled = bool.Parse(node.SelectSingleNode("user/contributors_enabled").InnerText);
            status.user = user;
            if (node.SelectSingleNode("retweeted_status") != null)
            {
                Status retweeted_status = new Status();
                createDt = node.SelectSingleNode("retweeted_status/created_at").InnerText;
                if (!string.IsNullOrEmpty(createDt))
                {
                    string[] sdtArr = createDt.Split(' ');
                    string newDt = string.Format("{0}, {1} {2} {3} {4}", sdtArr[0], sdtArr[2], sdtArr[1], sdtArr[5], sdtArr[3]);
                    retweeted_status.created_at = DateTime.Parse(newDt);
                }
                retweeted_status.id = node.SelectSingleNode("retweeted_status/id").InnerText;
                retweeted_status.text = node.SelectSingleNode("retweeted_status/text").InnerText;
                retweeted_status.source = node.SelectSingleNode("retweeted_status/source").InnerText;
                retweeted_status.favorited = node.SelectSingleNode("retweeted_status/favorited").InnerText;
                retweeted_status.truncated = bool.Parse(node.SelectSingleNode("retweeted_status/truncated").InnerText);
                retweeted_status.in_reply_to_status_id = node.SelectSingleNode("retweeted_status/in_reply_to_status_id").InnerText;
                retweeted_status.in_reply_to_user_id = node.SelectSingleNode("retweeted_status/in_reply_to_user_id").InnerText;
                retweeted_status.in_reply_to_screen_name = node.SelectSingleNode("retweeted_status/in_reply_to_screen_name").InnerText;
                retweeted_status.small_pic = node.SelectSingleNode("retweeted_status/small_pic").InnerText;
                retweeted_status.middle_pic = node.SelectSingleNode("retweeted_status/middle_pic").InnerText;
                retweeted_status.original_pic = node.SelectSingleNode("retweeted_status/original_pic").InnerText;
                user = new User();
                user.id = node.SelectSingleNode("retweeted_status/user/id").InnerText;
                user.screen_name = node.SelectSingleNode("retweeted_status/user/screen_name").InnerText;
                user.name = node.SelectSingleNode("retweeted_status/user/name").InnerText;
                user.location = node.SelectSingleNode("retweeted_status/user/location").InnerText;
                user.description = node.SelectSingleNode("retweeted_status/user/description").InnerText;
                user.url = node.SelectSingleNode("retweeted_status/user/url").InnerText;
                user.profile_image_url = node.SelectSingleNode("retweeted_status/user/profile_image_url").InnerText;
                user._protected = bool.Parse(node.SelectSingleNode("retweeted_status/user/protected").InnerText);
                user.followers_count = node.SelectSingleNode("retweeted_status/user/followers_count").InnerText;
                user.friends_count = node.SelectSingleNode("retweeted_status/user/friends_count").InnerText;
                user.favourites_count = node.SelectSingleNode("retweeted_status/user/favourites_count").InnerText;
                user.statuses_count = node.SelectSingleNode("retweeted_status/user/statuses_count").InnerText;
                user.following = bool.Parse(node.SelectSingleNode("retweeted_status/user/following").InnerText);
                user.verified = bool.Parse(node.SelectSingleNode("retweeted_status/user/verified").InnerText);
                user.contributors_enabled = bool.Parse(node.SelectSingleNode("retweeted_status/user/contributors_enabled").InnerText);
                retweeted_status.user = user;
                status.retweeted_status = retweeted_status;
            }
            return status;
        }
        /// <summary>
        /// @我的
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static List<Status> MentionsTimeline(string name, string pwd, int page)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/mentions_timeline.xml?page={0}&count=20", page);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取@我的微博列表失败！");
            List<Status> ltStatus = GetStatus(xml);
            return ltStatus;
        }
        /// <summary>
        /// @我的 是否有下一页
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public static bool MentionsTimelineNextPage(string name, string pwd, int page)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/mentions_timeline.xml?page={0}&count=20", page + 1);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取下一页失败！");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList statuses = doc.SelectNodes("/statuses/status");
            if (statuses.Count == 0)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 发布文字微博
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="status"></param>
        public static void Update(string name, string pwd, string status)
        {
            string url = "http://api.t.sohu.com/statuses/update.xml";
            string postData = string.Format("status={0}", HttpUtility.UrlEncode(status));
            string xml = HttpPost(name, pwd, url, postData);
            if (xml.Contains("<error>"))
                throw new Exception("发布文字微博失败！");
        }
        /// <summary>
        /// 转发一条微博
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="in_reply_to_status_id"></param>
        /// <param name="status"></param>
        public static void Transmit(string name, string pwd, string transmit_status_id, string status)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/transmit/{0}.xml", transmit_status_id);
            string postData = string.Format("status={0}", HttpUtility.UrlEncode(status));
            string xml = HttpPost(name, pwd, url, postData);
            if (xml.Contains("<error>"))
                throw new Exception("转发失败！");
        }
        /// <summary>
        /// 用户首页
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public static List<Status> FriendsTimeline(string name, string pwd, int page)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/friends_timeline.xml?page={0}&count=20", page);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取我的首页失败！");
            List<Status> ltStatus = GetStatus(xml);
            return ltStatus;
        }
        /// <summary>
        /// 用户首页是否有下一页
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="passwd"></param>
        /// <param name="count"></param>
        /// <param name="page"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static bool NextPage(string name, string pwd, int page)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/friends_timeline.xml?page={0}&count=20", page + 1);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取下一页失败！");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList statuses = doc.SelectNodes("/statuses/status");
            if (statuses.Count == 0)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 获取指定用户的微博列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public static List<Status> UserTimeline(string name, string pwd, string user_id, int count)
        {
            string url = string.Format("http://api.t.sohu.com/statuses/user_timeline/{0}.xml?page=1&count={1}", user_id, count);
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取用户微博列表失败！");
            List<Status> ltStatus = GetStatus(xml);
            return ltStatus;
        }
        /// <summary>
        /// 公共微博，最新发布的50条微博列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static List<Status> PublicTimeline(string name, string pwd)
        {
            string url = "http://api.t.sohu.com/statuses/public_timeline.xml";
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取公共微博失败！");
            List<Status> ltStatus = GetStatus(xml);
            return ltStatus;
        }
        /// <summary>
        /// 得到状态列表
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private static List<Status> GetStatus(string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList list = doc.SelectNodes("/statuses/status");
            List<Status> ltStatus = new List<Status>();
            foreach (XmlNode node in list)
            {
                Status status = new Status();
                string createDt = node.SelectSingleNode("created_at").InnerText;
                if (!string.IsNullOrEmpty(createDt))
                {
                    string[] sdtArr = createDt.Split(' ');
                    string newDt = string.Format("{0}, {1} {2} {3} {4}", sdtArr[0], sdtArr[2], sdtArr[1], sdtArr[5], sdtArr[3]);
                    status.created_at = DateTime.Parse(newDt);
                }
                status.id = node.SelectSingleNode("id").InnerText;
                status.text = node.SelectSingleNode("text").InnerText;
                status.source = node.SelectSingleNode("source").InnerText;
                status.favorited = node.SelectSingleNode("favorited").InnerText;
                status.truncated = bool.Parse(node.SelectSingleNode("truncated").InnerText);
                status.in_reply_to_status_id = node.SelectSingleNode("in_reply_to_status_id").InnerText;
                status.in_reply_to_user_id = node.SelectSingleNode("in_reply_to_user_id").InnerText;
                status.in_reply_to_screen_name = node.SelectSingleNode("in_reply_to_screen_name").InnerText;
                status.in_reply_to_status_text = node.SelectSingleNode("in_reply_to_status_text").InnerText;
                status.small_pic = node.SelectSingleNode("small_pic").InnerText;
                status.middle_pic = node.SelectSingleNode("middle_pic").InnerText;
                status.original_pic = node.SelectSingleNode("original_pic").InnerText;
                User user = new User();
                user.id = node.SelectSingleNode("user/id").InnerText;
                user.screen_name = node.SelectSingleNode("user/screen_name").InnerText;
                user.name = node.SelectSingleNode("user/name").InnerText;
                user.location = node.SelectSingleNode("user/location").InnerText;
                user.description = node.SelectSingleNode("user/description").InnerText;
                user.url = node.SelectSingleNode("user/url").InnerText;
                user.profile_image_url = node.SelectSingleNode("user/profile_image_url").InnerText;
                user._protected = bool.Parse(node.SelectSingleNode("user/protected").InnerText);
                user.followers_count = node.SelectSingleNode("user/followers_count").InnerText;
                user.friends_count = node.SelectSingleNode("user/friends_count").InnerText;
                user.favourites_count = node.SelectSingleNode("user/favourites_count").InnerText;
                user.statuses_count = node.SelectSingleNode("user/statuses_count").InnerText;
                user.following = bool.Parse(node.SelectSingleNode("user/following").InnerText);
                user.verified = bool.Parse(node.SelectSingleNode("user/verified").InnerText);
                user.contributors_enabled = bool.Parse(node.SelectSingleNode("user/contributors_enabled").InnerText);
                status.user = user;
                ltStatus.Add(status);
            }
            return ltStatus;
        }
        /// <summary>
        /// 是否到达访问上限
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool IsLimit(string name, string pwd, out string msg)
        {
            Hash hash = RateLimitStatus(name, pwd);
            if (hash.remaining_hits <= 4)
            {
                TimeSpan ts = hash.reset_time - DateTime.Now;
                msg = string.Format("您本小时内的访问次数已达到上限，请您在今日 {0} 后继续访问。距离 {0} 还剩 {1}分钟！", hash.reset_time.ToString("HH:mm"), ts.Minutes);
                return true;
            }
            else
            {
                msg = null;
                return false;
            }
        }
        /// <summary>
        /// 获取访问上限信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static Hash RateLimitStatus(string name, string pwd)
        {
            string url = "http://api.t.sohu.com/account/rate_limit_status.xml";
            string xml = HttpGet(name, pwd, url);
            if (xml.Contains("<error>"))
                throw new Exception("获取访问上限失败！");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            Hash hash = new Hash();
            hash.remaining_hits = Convert.ToInt32(doc.SelectSingleNode("/hash/remaining-hits").InnerText);
            hash.hourly_limit = Convert.ToInt32(doc.SelectSingleNode("/hash/hourly-limit").InnerText);
            hash.reset_time_in_seconds = Convert.ToInt32(doc.SelectSingleNode("/hash/reset-time-in-seconds").InnerText);

            string sdt = doc.SelectSingleNode("/hash/reset-time").InnerText;
            if (!string.IsNullOrEmpty(sdt))
            {
                string[] sdtArr = sdt.Split(' ');
                string newDt = string.Format("{0}, {1} {2} {3} {4}", sdtArr[0], sdtArr[2], sdtArr[1], sdtArr[5], sdtArr[3]);
                hash.reset_time = DateTime.Parse(newDt);
            }
            return hash;
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static bool VerifyCredentials(string name, string pwd, out string user_id, out string screen_name)
        {
            user_id = "";
            screen_name = "";
            string url = "http://api.t.sohu.com/account/verify_credentials.xml";
            try
            {
                string xml = HttpGet(name, pwd, url);
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
                user_id = doc.SelectSingleNode("/user/id").InnerText;
                screen_name = doc.SelectSingleNode("/user/screen_name").InnerText;
                return true;
            }
            catch (Exception)
            {
                user_id = null;
                return false;
            }
        }
        /// <summary>
        /// GET DATA
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private static string HttpGet(string name, string pwd, string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(name + ":" + pwd));
            request.Method = "GET";
            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    string result = sr.ReadToEnd();
                    return result;
                }
            }
        }
        /// <summary>
        /// POST DATA
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        private static string HttpPost(string name, string pwd, string url, string postData)
        {
            WebRequest request = WebRequest.Create(url);
            request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(name + ":" + pwd));
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
            {
                sw.Write(postData);
                sw.Flush();
            }
            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    string result = sr.ReadToEnd();
                    return result;
                }
            }
        }
    }
}